import React, {Component} from 'react';
import {SingleElectricityLine} from '@/components/Chart/ElectricityLine.ts';
import {queryDeviceWisdomElectricityCurrent} from '../service';
import {getQueryString} from '@/utils/util';
import { SingleFigure } from '@/components/Chart/Figure';

function flatten(arr, result = []) {
  for (let item of arr) {
      if (Array.isArray(item))
          flatten(item, result)
      else
          result.push(item)
  }
  return result
}

const groupBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
    acc[val] = (acc[val] || []).concat(arr[i]);
    return acc;
  }, {});


export default class WaveformFigureRight extends Component {

  state = {
    id: getQueryString('id'),
    electricityLine: null,
    temperatureOne: [],
    temperatureTwo: [],
    temperatureThree: [],
    temperatureFour: [],
    xAxisData: []
  };

  componentDidMount() {
    queryDeviceWisdomElectricityCurrent({deviceId: this.state.id}).then(data => {
      let dataX = [];
      const color = ['#f98b55', '#ffb53e', '#2dcef0', '#49a1ff']
      const ans = groupBy(
        flatten(
          data.map(it => 
              Object.keys(it.valueMap)
                .filter(v => v.indexOf("temperature") == 0)
                .map(u => {
                  dataX.push(it.createTime)
                  return ({key: u, value: it.valueMap[u]})
                })
          )
      ), 'key')
      
      const v = Object.values(ans).map((it:Array<{value: string}>, index) => ({
        name:`温度${index+1}/°C`,
        type:'line',
        color: color[index],
        data: it.map(u => u.value)
      }))
      
      SingleFigure({
        ref: this.state.electricityLine,
        color,
        legend: ['温度/°C'],
        dataX: [...new Set(dataX)],
        data: v
      })
    });
  }

  render() {
    return (
      <div>
        <div ref={(value) => this.state.electricityLine = value} style={{'height': '400px'}}></div>
      </div>
    )
  }
}
